<template>
  <main class="form-signin">
    <form>
      <br>
      <br>
      <img class="mb-4" src="../assets/update.svg" alt="" width="72" height="57">
      <h1 class="h3 mb-3 fw-normal">Update Your Information</h1>

      <div class="form-floating">
        <input type="tel" class="form-control" id="floatingTel" placeholder=" " readonly v-model="tel">
        <label for="floatingTel">Telephone</label>
      </div>
      <div class="form-floating">
        <input type="text" class="form-control" id="floatingName" placeholder=" " v-model="name">
        <label for="floatingName">Name</label>
      </div>
      <div class="form-floating">
        <input type="text" class="form-control" id="floatingAddress" placeholder=" " v-model="address">
        <label for="floatingAddress">Address</label>
      </div>
      <div class="form-floating">
        <input type="password" class="form-control" id="floatingPassword" placeholder=" "  @focus="clear" v-model="newPwd">
        <label for="floatingPassword">Password</label>
      </div>
      <br>
      <br>
      <button type="button" class="w-100 btn btn-lg btn-primary" @click="update">Update</button>
    </form>
  </main>
</template>

<script>
import axios from "axios";
import {ref} from 'vue';
import {useRouter} from "vue-router";
import {useStore} from "vuex";

export default {
  name: "updateInfo",
  setup(){
    const store = useStore();
    const router = useRouter();
    store.dispatch("Load");

    let name = ref("");
    let address = ref("");
    let pwd = ref("");
    let newPwd = ref("");
    let tel = ref("");
    axios({
      url:"GetInfoServlet"
    }).then((res)=>{
      let user = res.data;
      tel.value = user['telephone'];
      name.value = user['name'];
      address.value = user['address'];
      pwd.value = user['pwd'];
      newPwd.value = "****************";
    })

    const update = ()=>{
      if(newPwd.value !== "****************"){
        pwd.value = newPwd.value;
      }
      axios({
        url:"UpdateUserInfoServlet",
        params:{
          name:name.value,
          address:address.value,
          pwd:pwd.value
        },
        async:false
      }).then(()=>{
        router.push("/books")
      })
    }
    const clear = ()=>{
      newPwd.value = "";
    }
    store.dispatch("Finished")
    return{
      name,
      address,
      pwd,
      newPwd,
      tel,
      update,
      clear
    }
  }
}
</script>

<style scoped>
.form-signin {
  width: 100%;
  max-width: 330px;
  padding: 15px;
  margin: auto;
}

.form-signin .checkbox {
  font-weight: 400;
}

.form-signin .form-floating:focus-within {
  z-index: 2;
}

.form-signin input[type="tel"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
</style>